import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'
import {getToken} from "./utils/auth";
// progress bar style

NProgress.configure({ showSpinner: false })// NProgress Configuration

//白名单
const whiteList = ['/login', '/404',]
router.beforeEach((to, from, next) => {
  NProgress.start() // start progress bar

  if(whiteList.indexOf(to.path)!=-1){
    next();
  }else {
    if(getToken()){
      if(store.getters.addRouters.length==0){
        store.dispatch('getMenu').then(() => { // 根据roles权限生成可访问的路由表
          // 动态添加可访问路由表
          router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
        });
      }
      // console.log(to.path)
      //
      next()
      NProgress.done()
      //   let rs= hasRouter(to.path,store.getters.addRouters)
      //
      // if(rs){
      //   next()
      // }else {
      //   // console.log(from)
      //   alert('权限不足')
      //   next('/')
      //   // next();
      //   NProgress.done()
      // }
    }else {
      next('/login') // 否则全部重定向到登录页
      NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
    }
  }
})

router.afterEach(() => {
  NProgress.done() // finish progress bar
})
// 判断是否有权限
function hasRouter(path,routerArray){
  console.log(routerArray)
   for(var i=0;i<routerArray.length;i++){

     if(routerArray[i].path==path){
         return true;
     }else {
        if(routerArray[i].children){
        if(hasRouter(path,routerArray[i].children)){
          return true;
           };
        }
     }
   }
}
